<?php
namespace Common\Model;

use Think\Model;

/**
 * 数据库配置
 *
 * @author codebean
 *
 */
class ConfigModel extends Model
{

    protected $tableName = 'config';

    /**
     * 获取$key的值
     * @param unknown $key
     */
    public function gets($key)
    {
        $where = array();
        $where['key'] = $key;
        return $this->where($where)->find();
    }

    /**
     * 设置$key的值为$val
     * @param unknown $key
     * @param unknown $val
     */
    public function sets($key, $val)
    {
        if (is_array($val)) {
            $val = serialize($val);
        }
        $rs = $this->gets($key);
        if ($rs) {
            $where = array();
            $where['id'] = $rs['id'];
            
            $data = array();
            $data['value'] = $val;
            $data['update_time'] = date("Y-m-d H:i:s");
            return $this->where($where)->save($data);
        } else {
            $data = array();
            $data['key'] = $key;
            $data['value'] = $val;
            $data['update_time'] = date("Y-m-d H:i:s");
            return $this->add($data);
        }
    }

    /**
     * 获取所有的配置
     */
    public function getAll()
    {
        $config = D("Config");
        $datas = $config->select();
        $data = array();
        foreach ($datas as $k => $v) {
            $data[$v['key']] = htmlspecialchars_decode($v['value']);
        }
        return $data;
    }

    public function getConfig($key)
    {
        $data = $this->gets($key);
        return $data['value']?$data['value']:false;
    }
    
    public function getConfigs($keys)
    {
        $ret = array();
        $where = array();
        $where['key'] = array('IN',$keys);
        $data =  $this->where($where)->select();
        if( $data ){
            foreach ($data as $item)
            {
                $ret[ $item['key'] ] = $item['value']? $item['value'] :false;
            }
        }
        return $ret;
    }

    public function setConfig($key, $val)
    {
        return $this->sets($key, $val);
    }
}